package com.bingxue.edu.tools;

import com.bingxue.edu.common.enums.ChangeTypeEnum;
import com.bingxue.edu.management.education.model.entity.EnrollChangeRecord;
import com.bingxue.edu.management.education.service.EnrollChangeRecordService;
import com.bingxue.edu.management.shop.model.entity.Refund;
import com.bingxue.edu.management.shop.service.RefundService;
import com.mybatisflex.core.row.Db;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

import static cn.hutool.core.date.DatePattern.PURE_DATETIME_FORMATTER;
import static com.bingxue.edu.management.education.model.entity.table.EnrollChangeRecordTableDef.ENROLL_CHANGE_RECORD;
import static com.bingxue.edu.management.shop.model.entity.table.RefundTableDef.REFUND;

/**
 * @author panbo
 * @since 2024/11/28
 */
@SpringBootTest
public class RefundTimeFixedTool {

    @Autowired
    private RefundService refundService;

    @Autowired
    private EnrollChangeRecordService enrollChangeRecordService;

//    @Test
//    @Transactional(rollbackFor = Exception.class)
    public void fixed() {
        List<Refund> list = refundService.queryChain()
                .where(REFUND.ID.likeLeft("5"))
                .list();
        for (Refund refund : list) {
            String oldId = refund.getId();
            String newId = refund.getRefundTime().format(PURE_DATETIME_FORMATTER) + "000000";
            System.out.println("old id: " + oldId + " new id: " + newId);
            EnrollChangeRecord record = enrollChangeRecordService.queryChain()
                    .where(ENROLL_CHANGE_RECORD.CHANGE_TYPE.in(ChangeTypeEnum.CANCEL_CLASS, ChangeTypeEnum.CANCEL_LESSON))
                    .and(ENROLL_CHANGE_RECORD.BUSINESS_ID.eq(oldId))
                    .one();
            if(record == null) {
                System.out.println("record is null: " + oldId);
                continue;
            }
            String sql = "update shop_refund set id=? where id=?";
            int i = Db.updateBySql(sql, newId, oldId);
//            boolean update = refundService.updateChain()
//                    .where(REFUND.ID.eq(oldId))
//                    .set(REFUND.ID, newId)
////                    .set(REFUND.UPDATE_TIME, record.getUpdateTime())
////                    .set(REFUND.UPDATE_USER, record.getUpdateUser())
//                    .update();
            if(i > 0) {
                String sql2 = "update edu_enroll_change_record set business_id=? where id=?";
                int ii = Db.updateBySql(sql2, newId, record.getId());
                if(ii > 0) {
                    System.out.println("success: " + oldId);
                }
            } else {
                System.out.println("not update: " + oldId);
            }
        }
    }

}
